package com.tuzhi.base.web.advice;

import com.alibaba.fastjson2.JSON;
import com.tuzhi.base.web.annotation.GlobalApiResultJson;
import com.tuzhi.base.web.annotation.IgnoreGlobalResponseHandler;
import com.tuzhi.common.domain.ResultBO;
import com.tuzhi.common.helper.ResultHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 实现ResponseBodyAdvice接口，可以对返回值在输出之前进行修改
 * 统一返回结果
 */
// 如果引入了swagger或knife4j的文档生成组件，这里需要仅扫描自己项目的包，否则文档无法正常生成
//@RestControllerAdvice(basePackages = "*.controller")
@RestControllerAdvice
public class GlobalResponseHandler implements ResponseBodyAdvice<Object> {
    Logger logger = LoggerFactory.getLogger(GlobalResponseHandler.class);

    //判断支持的类型
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        // 检查注解是否存在，存在则忽略拦截
        if (methodParameter.getDeclaringClass().isAnnotationPresent(IgnoreGlobalResponseHandler.class)) {
            return false;
        }
        if (methodParameter.getMethod().isAnnotationPresent(IgnoreGlobalResponseHandler.class)) {
            return false;
        }
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType,
                                  Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest,
                                  ServerHttpResponse serverHttpResponse) {
        if (methodParameter.getDeclaringClass().isAnnotationPresent(GlobalApiResultJson.class)
                || methodParameter.getMethod().isAnnotationPresent(GlobalApiResultJson.class)) {
            //如果需要中全局统一Json结果处理，则返回全局统一Json
            // 判断为null构建ResponseData对象进行返回
            if (o == null) {
                return ResultHelper.success(null);
            }
            // 判断是ResponseData子类或其本身就返回Object o本身，因为有可能是接口返回时创建了ResponseData,这里避免再次封装
            if (o instanceof ResultBO) {
                return o;
            }
            // String特殊处理，否则会抛异常
            if (o instanceof String) {
                //因为最终是调用StringHttpMessageConverter写回数据不是String的话会报错，则最终的Content-Type 是 text/plain
                return JSON.toJSON(ResultHelper.success("成功", o)).toString();
            }
            return ResultHelper.success("成功", o);
        }
        return o;
    }
}
